#include "threadpool.h"
int exitPipe[2];

void handler(int signum){
    printf("signum = %d\n",signum);
    write(exitPipe[1],"exit",4);
}

int main(int argc, char *argv[])
{
    // ./server 192.168.153.129 55555
    ARGS_CHECK(argc,3);
    pipe(exitPipe);
    if(fork()){
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("process exit\n");
        return 0;
    }
    close(exitPipe[1]);
    threadPool_t pool;
    memset(&pool,0,sizeof(pool));
    thread_pool_init(&pool);
    make_worker(&pool);
    MYSQL* mysql = mysql_init(NULL);
    MYSQL* ret = mysql_real_connect(mysql,"localhost","root","2001.04.07","networkdisk",0,NULL,0);
    if(ret == NULL){
        fprintf(stderr,"%s:%s\n","mysql_real_connect",mysql_error(mysql));
        return -1;
    }


    int sockfd = tcp_init(argv[1],argv[2]);
    int epfd = epoll_create(1);
    epoll_add(epfd,sockfd);
    epoll_add(epfd,exitPipe[0]);
    struct epoll_event readyset[1];
    
    userlist_t userlist;
    linklist_init(&userlist);

    int netfd = -1;
    train_t train;
    
    while(1){
        epoll_wait(epfd,readyset,1,-1);
        if(readyset->data.fd == sockfd){
            netfd = accept(sockfd,NULL,NULL);
            epoll_add(epfd,netfd);
            linklist_insert(&userlist,netfd,NULL);
        }
        else if(readyset->data.fd == exitPipe[0]){
            pthread_mutex_lock(&pool.mutex);
            pool.exitFlag = 1;
            pthread_cond_broadcast(&pool.cond);
            pthread_mutex_unlock(&pool.mutex);

            for(int i = 0; i < pool.threadNum; i++){
                pthread_join(pool.childThreadSet[i],NULL);
                printf("thread exit\n");
            }
            return 0;
        }
        else{
            memset(&train,0,sizeof(train_t));
            int ret = recv(readyset->data.fd,&train.command,sizeof(train.command),0);
            if(ret == 0){
                printf("client disconnect\n");
                close(readyset->data.fd);
                break;
            }
            recv(readyset->data.fd,&train.length,sizeof(train.length),0);
            if(train.length != 0){
                recv(readyset->data.fd,train.data,train.length,0);
            }
            switch(train.command){
            case CD:break;
            case PWD:break;
            case LS:break;
            case MKDIR:break;
            case RMDIR:break;
            case PUTS:break;
            case GETS:break;
            case REMOVE:break;
            case QUIT:break;
            case LOGIN:break;
            case REGISTER:break;
            default:break;
            }

        }
    }
    return 0;
}

